import 'package:drm/base/info_item_view.dart';
import 'package:drm/base/page.dart';
import 'package:drm/base_bloc/save_info_entity.dart';
import 'package:drm/dialog/date_time_dialog.dart';
import 'package:drm/http/http_url.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import 'azd_bean.dart';
import 'azd_bloc.dart';
import 'azd_mx_entity.dart';




class AzdInfoPage extends StatefulWidget {
  final String title;
  final AzdBean azdBean;
  final bool enable;

  AzdInfoPage({key, this.title, this.azdBean, this.enable = false})
      : super(key: key);

  @override
  _AzdInfoPageState createState() {
    return _AzdInfoPageState();
  }
}

class _AzdInfoPageState extends PageState<AzdInfoPage> {
  GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
  List<Widget> actions;

  AzdBloc _azdBloc = AzdBloc();
  TextEditingController _textEditingController;
  List<AzdMxEntity> items = [];
  InfoRow _azdSjaz;

  String _sjaz = '';

  String _bz = '';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _textEditingController = TextEditingController();
    if (widget.enable) {
      actions = [
        IconButton(
          icon: Icon(Icons.check),
          onPressed: () {
            save();

          },
        )
      ];
    } else {
      actions = null;
    }

    if (widget.azdBean.lx == '整机') {
      getData();
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _textEditingController.dispose();
    _azdBloc.dispose();
  }

  @override
  addBlocToBlocList() {}

  @override
  Widget mainView(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: Text(widget.title), centerTitle: true, actions: actions),
      body: homePage(context),
    );
  }

  InfoRow iniAzdSjaz(BuildContext context) {
    _azdSjaz = InfoRow('实际安装',
        onGetValue: (value) {
          _sjaz = value;
        },
        textEditingController: _textEditingController,
        infoRowType: InfoRowType.TEXT,
        value: widget.azdBean.sJAZ,
        enable: widget.enable,
        onPress: () {
          DateTimeDialog.showPickerFullDate(context, widget.azdBean.sJAZ,
              (valueInfo) {
            setState(() {
              _textEditingController.text = valueInfo;
            });
          });
        });

    return _azdSjaz;
  }

  Widget homePage(BuildContext context) {
    return Form(
        key: _formKey,
        child: ListView(
          children: <Widget>[

            BlocListener(bloc: _azdBloc, listener: (context,state) {
              hideLoading();
              if (state is AzdSaveState) {
                print('返回状态为：${state.reuslt.isSuccess}');
                if (state.reuslt.isSuccess) {
                  SaveInfoEntity result = state.reuslt.data ;
                  showToast(result.info);
                  if (result.info == '保存成功') {
                    Navigator.of(context).pop(true);
                  }
                }else {
                  showToast('保存失败');
                }
              }

            },child:  Container(),),
            iniAzdSjaz(context),
            InfoRow('备注', onGetValue: (value) {
              print(value);
              _bz = value;
            },
                infoRowType: InfoRowType.TEXTFIELD,
                maxLines: 5,
                orientation: MyOrientation.vertical,
                enable: widget.enable,
                value: widget.azdBean.aznr,
                height: null,
                textAlign: TextAlign.start),
            iniListView(context),
          ],
        ));
  }

  Widget iniListView(BuildContext context) {
    print(widget.azdBean.lx);
    if (widget.azdBean.lx == '整机') {
      return Column(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.only(top: 5),
            child: Container(
              color: Colors.white,
              height: 40,
              alignment: Alignment.centerLeft,
              child: Padding(
                  padding: EdgeInsets.only(left: 16),
                  child: Text('请录入整机安装的具体位置、水源、水压。')),
            ),
          ),
          BlocBuilder(
              bloc: _azdBloc,
              builder: (context, state) {
                hideLoading();
                if (state is AzdLoadMxState) {
                  if (state.reuslt.isSuccess) {
                    items = state.reuslt.data;
                  } else {
                    items = [];
                  }

                }
                return ListView(
                    physics: new NeverScrollableScrollPhysics(),
                    //增加
                    shrinkWrap: true,
                    children: items.map((item) {
                      return Column(
                        children: <Widget>[
                          InfoRow('编号/货号',
                              value: item.cPBH,
                              infoRowType: InfoRowType.TEXT,
                              enable: false),
                          InfoRow('唯一码',
                              value: item.wYM,
                              infoRowType: InfoRowType.TEXT,
                              enable: false),
                          InfoRow('安装位置',
                              value: item.aZWZ, enable: widget.enable,onGetValue: (value) => item.aZWZ = value,),
                          InfoRow(
                            '水源',
                            value: item.sY,
                            enable: widget.enable,
                            onGetValue: (value) => item.sY = value,
                          ),
                          InfoRow('水压',
                              value: item.sYA,
                              enable: widget.enable,
                              onGetValue: (value) => item.sYA = value),
                        ],
                      );
                    }).toList());
              })
        ],
      );
    } else {
      return Container();
    }
  }

  void getData() {
    //Type=AZD_AZMX  //安装单---安装位置,水源,水压等信息
    //
    //传参：XSDNumber（销售单号），CPBH（产品编号），SX(产品颜色)
    showLoading();
    Map<String, String> params = Map();
    if (widget.azdBean.zT == '已派工') {
      params.putIfAbsent('Type', () => 'GetWYM_CPBH');
    } else {
      params.putIfAbsent('Type', () => 'AZD_AZMX');
    }
    params.putIfAbsent('XSDNumber', () => '${widget.azdBean.xDSD}');
    params.putIfAbsent('CPBH', () => '${widget.azdBean.cPBH}');
    params.putIfAbsent('SX', () => '${widget.azdBean.sx}');

    _azdBloc.dispatch(AzdLoadMxEvent(params, AppUrl.getGdfk()));
  }

  void save() {
    var form = _formKey.currentState;
    form.save();

    if(_sjaz == '') {
        showToast('请选择安装日期');
        return ;
    }


    String inserted = '' ;
    if(items != null || items.length > 0) {
      List insertData = items.map((item) => item.toJson()).toList();
      StringBuffer stringBuffer = StringBuffer() ;
      insertData.forEach((item){
        if (stringBuffer.toString().isNotEmpty) {
          stringBuffer.write(',');
        }
        stringBuffer.write(item.toString());
      });
      inserted = '[${stringBuffer.toString()}]';
    }


    showLoading();
    Map<String, String> params = Map();
    params.putIfAbsent('Type', () => 'AZD_ADD');
    params.putIfAbsent('AZNR', () => '${_bz}');
    params.putIfAbsent('XSDNumber', () => '${widget.azdBean.xDSD}');
    params.putIfAbsent('CPBH', () => '${widget.azdBean.cPBH}');
    params.putIfAbsent('SJAZ', () => '${_sjaz}');
    params.putIfAbsent('SX', () => '${widget.azdBean.sx}');
    params.putIfAbsent('inserted', () => '${inserted}');

    print(params.toString());

    _azdBloc.dispatch(AzdSaveEvent(params, AppUrl.getGdfk()));
  }
}
